package com.sky.service.impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Dish;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.ParamMissException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

import static com.sky.constant.PasswordConstant.DEFAULT_PASSWORD;
import static com.sky.constant.StatusConstant.ENABLE;


@Service
@Slf4j
@Transactional
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        String s = DigestUtils.md5Hex(password);

        if (!s.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    @Override
    public PageResult findById(EmployeePageQueryDTO employeePageQueryDTO) {
        Integer page = employeePageQueryDTO.getPage();
        Integer pageSize = employeePageQueryDTO.getPageSize();

        PageHelper.startPage(page, pageSize);


        Page<Employee> dish = employeeMapper.findByPage(employeePageQueryDTO); //后面 limit 0,10

        long total = dish.getTotal();//总记录数
        int pages = dish.getPages();//总页数
        List result = dish.getResult(); //本页数据

        //4.封装PageResultVo
        PageResult pageResultVo = new PageResult();
        //PageResult.setTotal(total);
        //PageResult.setRecords
        pageResultVo.setTotal(total);
        pageResultVo.setRecords(result);
        // Result re = new Result();
        return pageResultVo;
    }

    @Override
    public Integer insertEmployee(EmployeeDTO employee) {
        if (StringUtils.isBlank(employee.getUsername()) || StringUtils.isBlank(employee.getPhone())) {
            throw new ParamMissException("传入参数缺失");
        }
        Employee emp = new Employee();
        BeanUtils.copyProperties(employee, emp);
        emp.setPassword(DigestUtils.md5Hex(DEFAULT_PASSWORD));
        emp.setCreateTime(LocalDateTime.now());
        emp.setStatus(ENABLE);
        Long currentId = BaseContext.getCurrentId();
        emp.setUpdateTime(LocalDateTime.now());
        emp.setCreateUser(currentId);
        emp.setUpdateUser(currentId);


        // employeeMapper.insertEmployee(employee);
        return employeeMapper.insertEmployee(emp);
    }

    @Override
    public Employee findById(Long id) {

        return employeeMapper.findById(id);
    }

    @Override
    public Integer updetaStatus(Integer status, Integer id) {

        return employeeMapper.updetaStatus(status, id);
    }

    @Override
    public Integer updateEmployee(EmployeeDTO employee) {
        Employee emp = new Employee();
        BeanUtils.copyProperties(employee, emp);
        return employeeMapper.updateEmployee(employee);
    }

    @Override
    public Integer updatePassword(PasswordEditDTO passwordEditDTO) {
        if (passwordEditDTO.getNewPassword().equals(passwordEditDTO.getOldPassword())){
            throw new PasswordErrorException("新密码不能与旧密码相同");
        }
        Long currentId = BaseContext.getCurrentId();

        Employee byId = employeeMapper.findById(currentId);
        String s = DigestUtils.md5Hex(passwordEditDTO.getOldPassword());


        if (!s.equals(byId.getPassword())) {
            throw new PasswordErrorException("旧密码输入错误");
        }
        String newPassword = DigestUtils.md5Hex(passwordEditDTO.getNewPassword());
        passwordEditDTO.setNewPassword(newPassword);
       // Long currentId = BaseContext.getCurrentId();
        passwordEditDTO.setEmpId(currentId);
        Integer integer = employeeMapper.updatePassword(passwordEditDTO);
        return integer;
    }


}
